package com.yenlien.traceyun.plant.controller;

import com.yenlien.traceyun.business.entity.Equipment;
import com.yenlien.traceyun.business.service.EquipmentService;
import com.yenlien.traceyun.business.service.rest.usercenter.UserRestService;
import com.yenlien.traceyun.business.utils.EasyPoiUtils;
import com.yenlien.traceyun.plant.dao.CompanyDao;
import com.yenlien.traceyun.plant.dao.ShiJiRuiTongDao;
import com.yenlien.traceyun.plant.entity.Company;
import com.yenlien.traceyun.plant.entity.DevAlarm;
import com.yenlien.traceyun.plant.entity.DevThreshold;
import com.yenlien.traceyun.plant.entity.ShiJiRuiTong;
import com.yenlien.traceyun.plant.service.IotService;
import com.yenlien.traceyun.webase.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;

import static com.yenlien.traceyun.plant.utils.Tools.DATE_FORMATTER;

/**
 * @Date 2023/03/18
 * @Descript 新物联网平台（参照长武果园）
 */
@Api(tags = "物联网平台")
@RestController
@RequestMapping("/iot")
public class IOTController extends BaseController {

    @Autowired
    private ShiJiRuiTongDao shiJiRuiTongDao;
    @Autowired
    private EquipmentService equipmentService;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private IotService iotService;
    @Autowired
    private UserRestService userRestService;

    // 果园二期APP
    @GetMapping(value = "/getPlantData")
    @ApiOperation(value = "获取种植信息,", notes = "可选参数：companyId(企业ID, 不传则使用当前账号所属企业), plotId(地块ID, 不传则使用当前账号所属企业下的地块)")
    public Object getPlantData(String companyId, String plotId) {
        return success(iotService.getPlantData(companyId, plotId));
    }

    @GetMapping(value = "/getPlotByCompId")
    @ApiOperation(value = "获取该企业所有地块信息, 地块名称下拉列表", notes = "可选参数：companyId (不传就为当前登录账号所属企业)")
    public Object getPlotByCompId(String companyId) {
        return success(iotService.getPlotByCompId(companyId));
    }

    @GetMapping(value = "/getPlantBySoilId")
    @ApiOperation(value = "根据地块ID获取对应的种植信息已经农事操作信息", notes = "参数：soilId (地块id), 可选参数：plantName (种植名,模糊匹配)")
    public Object getPlantBySoilId(String soilId, String plantName) {
        return success(iotService.getPlantBySoilId(soilId, plantName));
    }

    @GetMapping(value = "/findUserById")
    @ApiOperation(value = "根据ID查询用户信息", notes = "参数：userId 用户ID")
    public Object findUserById(String userId) {
        return success(userRestService.findById(userId));
    }

    // 首页数据
    @GetMapping(value = "/getAppDevData")
    @ApiOperation(value = "app首页设备参数", notes = "可选参数：companyId (企业ID)")
    public Object getAppDevData(String companyId) {
        return success(iotService.getAppDevData(companyId));
    }

    @GetMapping(value = "/getVideoUrl")
    @ApiOperation(value = "获取世纪瑞通视频设备的播放地址", notes = "参数： devId(设备序列号), 可选参数：companyId (企业ID)")
    private Object getVideoUrl(String devId, String companyId){
        return success(iotService.getVideoUrl(devId, companyId));
    }
    @GetMapping(value = "/videoMove")
    @ApiOperation(value = "控制世纪瑞通监控变焦转向", notes = "参数： devId(设备序列号), val (Up:上；down:下；left:左；right:右；zoomin:放大；zoomout:缩小), 可选参数：companyId (企业ID)")
    private Object videoMove(String devId, String val, String companyId) {
        return success(iotService.videoMove(devId, val, companyId));
    }


    @GetMapping(value = "/getHistoryDevData")
    public Object getHistoryDevData(String devId, String paramName, String startTime, String endTime){
        return success(iotService.getHistoryDevData(devId, paramName, startTime, endTime));
    }

    // end







    @ApiOperation(value = "初始化地块及种植信息,农事信息，参数： companyId（当前企业ID）", notes = "")
    @GetMapping(value = "/init")
    public Object findAll(String companyId) {
        return iotService.findAll(companyId);
    }

    @ApiOperation(value = "为指定设备保存或修改阈值", notes = "")
    @PostMapping(value = "/saveThreshold")
    public Object saveThreshold(@RequestBody DevThreshold devThreshold) {
        return success(iotService.saveThreshold(devThreshold));
    }



    @ApiOperation(value = "分页搜索预警信息条件参数：paramName(参数名)  devName(设备名)  devId(设备序列号) alarmType(报警类型报警类型(1=参数异常 和 2=离线报警)) handleState(1=未处理，2=已处理)", notes = "")
    @PostMapping(value = "/findAlarmList")
    public Object findAlarmList(@RequestBody DevAlarm devAlarm) {
        return success(iotService.findAlarmList(devAlarm));
    }
    @ApiOperation(value = "不分页查询预警信息", notes = "条件参数：paramName(参数名)  devName(设备名)  devId(设备序列号) alarmType(报警类型) handleState(1=未处理，2=已处理)")
    @PostMapping(value = "/findAlarmNotPage")
    public Object findAlarmNotPage(@RequestBody DevAlarm devAlarm) {
        return success(iotService.findAlarmNotPage(devAlarm));
    }

    @ApiOperation(value = "获取预警信息中地块下拉框", notes = "参数：companyId")
    @PostMapping(value = "/getAlarmBaseSoil")
    public Object getAlarmBaseSoil(String companyId) {
        return success(iotService.getAlarmBaseSoil(companyId));
    }

    @ApiOperation(value = "批量处理预警信息, 参数： id集合", notes = "")
    @PostMapping(value = "/handle")
    public Object handle(@RequestBody List<String> idList) {
        iotService.handle(idList);
        return success("success");
    }

    @ApiOperation(value = "根据companyId和设备ID(equId)获取对应的阈值", notes = "")
    @GetMapping(value = "/getByEquId")
    public Object getByEquId(String companyId, String serial) {
        return success(iotService.getByEquId(companyId, serial));
    }


    @ApiOperation(value = "获取设备列表", notes = "companyId企业标识必传, devType用以限定类型可不传, 可选类型: 摄像机,土壤墒情,水质设备,气象传感,虫情监控,杀虫灯,无人机")
    @GetMapping(value = "/getDevList")
    private Object getDevList(@RequestParam("companyId") String companyId, String devType) {
        return success(iotService.getDevList(companyId, devType));
    }

    @ApiOperation(value = "分页获取视频列表", notes = "companyId企业标识必传, 可选：pageNum(页码), pageSize(每页数量), group(分组，等值匹配), name=设备名(模糊匹配)")
    @GetMapping(value = "/getVideoDevList")
    private Object getVideoDevList(@RequestParam("companyId") String companyId, Integer pageNum, Integer pageSize, String group, String name) {
        return success(iotService.getVideoDevList(companyId, pageNum, pageSize, group, name));
    }
    @ApiOperation(value = "获取设备分组列表", notes = "companyId企业标识必传, devType用以限定类型可不传(不传则代表查询所有设备分组), 可选类型: 摄像机,土壤墒情,水质设备,气象传感,虫情监控,杀虫灯,无人机")
    @GetMapping(value = "/getDevGroupList")
    private Object getDevGroupList(@RequestParam("companyId") String companyId, String devType) {
        return success(iotService.getDevGroupList(companyId, devType));
    }


    @ApiOperation(value = "更换企业的物联网平台名称", notes = "")
    @PostMapping(value = "/saveName")
    public Object saveName(@RequestBody  Company company) {
        return success(companyDao.save(company));
    }


    @ApiOperation(value = "加载大屏数据，参数： companyId （当前企业ID，不传则服务器获取当前用户所属企业）", notes = "")
    @GetMapping(value = "/getDevData")
    public Object getDevData(String companyId) {
        return success(iotService.getDevData(companyId));
    }



    @ApiOperation(value = "农事信息二级页面，参数： time (查询的时间), type (week=周, month=月, year=年)", notes = "")
    @GetMapping(value = "/getFarmData")
    public Object getFarmData(String time, String type) {
        return success(iotService.getFarmData(LocalDate.parse(time, DATE_FORMATTER), type));
    }





    @ApiOperation(value = "获取指定设备当前数据, devId(设备ID), devType(设备类型)", notes = "")
    @GetMapping(value = "/getNowData")
    public Object getNowData(String devId, String devType) {
        return success(iotService.getNowData(devId, devType));
    }


    @ApiOperation(value = "获取指定设备历史数据, devId(设备ID), devType(设备类型), 可选参数: startTime(开始时间), endTime(结束时间), page (页码), pageSize (每页条数)", notes = "")
    @GetMapping(value = "/getHistoryData")
    public Object getHistoryData(String devId, String devType, String startTime, String endTime, Integer page, Integer pageSize, String type) {
        return success(iotService.getHistoryData(devId, devType, startTime, endTime, page, pageSize, type));
    }





    @ApiOperation(value = "数据监测 devId(设备ID) 可选参数: startTime(开始时间), endTime(结束时间)", notes = "")
    @GetMapping(value = "/getLineData")
    public Object getLineData(String devId, String startTime, String endTime) {
        return success(iotService.getLineData(devId, startTime, endTime));
    }

    @ApiOperation(value = "数据监测数据导出 devId(设备ID) 可选参数: startTime(开始时间), endTime(结束时间)", notes = "")
    @GetMapping(value = "/exportLineData")
    public void exportLineData(String devId, String startTime, String endTime, HttpServletResponse response) throws IOException {
        iotService.exportLineData(devId, startTime, endTime, response);
    }


    @ApiOperation(value = "数据监测图表 devId(设备ID), paramName(参数名) 可选参数: startTime(开始时间), endTime(结束时间)", notes = "")
    @GetMapping(value = "/getLineData2")
    public Object getLineData2(String devId, String paramName, String startTime, String endTime) {
        return success(iotService.getByParamName(devId, paramName, startTime, endTime));
    }




//    @ApiOperation(value = "世纪瑞通视频旋转, devId(设备ID), val( Up:上；down:下；left:左；right:右；zoomin:放大；zoomout:缩小 )", notes = "")
//    @GetMapping(value = "/videoMove")
//    private Object videoMove(String devId, String val) {
//        Equipment equipment = equipmentService.findById(devId);
//        String token = GetCWDevData.getToken(equipment.getAppKey(), equipment.getAppSecret());
//        return success(GetCWDevDataSF.videoMove(equipment.getSerial(), val, token));
//    }


    @GetMapping(value = "/export")
    public void export(String devId, String startTime, String endTime, HttpServletResponse response) {
        Equipment equipment = equipmentService.findByDevId(devId);
        List<ShiJiRuiTong> dataList;
        if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            dataList = shiJiRuiTongDao.getHistoryData(equipment.getId(), startTime, endTime);
        } else {
            dataList = shiJiRuiTongDao.getHistoryData(equipment.getId());
        }
        try {
            EasyPoiUtils.exportExcel(dataList, "设备数据", "设备数据", ShiJiRuiTong.class, "设备数据", response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 牛王村
    @ApiOperation(value = "根据企业ID获取设备列表", notes = "可选参数: companyId (默认值: 牛王村账号)")
    @GetMapping(value = "/getEquListByCompId")
    public Object getEquListByCompId(String companyId) {
        return success(iotService.getEquListByCompId(companyId));
    }


    @ApiOperation(value = "牛王村每个设备温湿度", notes = "")
    @GetMapping(value = "/getNwcDataList")
    public Object getNwcDataList() {
        return success(iotService.getNwcDataList());
    }

    @ApiOperation(value = "牛王村根据设备ID获取历史数据", notes = "参数: equId (设备ID), startTime(起始时间), endTime(结束时间)")
    @GetMapping(value = "/getHistoryByDevId")
    public Object getHistoryByDevId(String equId, String startTime, String endTime) {
        return success(iotService.getHistoryByDevId(equId, startTime, endTime));
    }


    @ApiOperation(value = "根据设备ID获取数据何对应的统计数据", notes = "参数；equId(设备ID), 可选统计参数: type[day=当日, week=周, month=月]。返回值: data(统计数据), dataList(当前值), cnt(总数)")
    @GetMapping(value = "/getDataById")
    public Object getDataById(String equId, String type) {
        return success(iotService.getDataById(equId, type));
    }





    // 果业大数据平台
    @ApiOperation(value = "获取果园企业信息,农业咨询,种植品类", notes = "normalFruitNum=普通果园数量, wisdomFruitNum=智慧果园数量, fruitNum=果园总数, " +
            "fruitComp=果园企业[name=企业名, fruitType=果园类型(1=普通果园  2=智慧果园)], news=文章, plantRatioList=种植品类占比, areaAll=总面积")
    @GetMapping(value = "/getInfo")
    public Object getInfo() {
        return success(iotService.getInfo());
    }


    @ApiOperation(value = "获取果业中心设备总数及状态", notes = "可选参数: companyId(若传递该参数则查询该企业下的设备)。 devCnt=设备总数, devState=在线情况 [type=类型, onlineNum=在线数量, totalNum=总数]")
    @GetMapping(value = "/getDevState")
    public Object getDevState(String companyId) {
        return success(iotService.getDevState(companyId));
    }





    // 新果业大数据平台
    @ApiOperation(value = "果业中心大屏获取产业园情况,园区动态,专家服务,种植品种,设备信息数据")
    @GetMapping(value = "/getHomeData")
    public Object getHomeData() {
        return success(iotService.getHomeData());
    }


    @ApiOperation(value = "果业中心大屏所有专家信息")
    @GetMapping(value = "/getAllExpert")
    public Object getAllExpert() {
        return iotService.getAllExpert();
    }

    // 销售与价格趋势
    @ApiOperation(value = "果业中心大屏销售与价格趋势", notes = "参数: type=周/月/半年, (startTime=起始时间, endTime=结束时间)(起始与结束两时间为组合参数与type传其一, 格式 yyyy-mm-dd)")
    @GetMapping(value = "/getPrice")
    public Object getPrice(String type, String startTime, String endTime) {
        return success(iotService.getPrice(type, startTime, endTime));
    }

    @ApiOperation(value = "设备二级页面", notes = "参数: type=镇/村/果园")
    @GetMapping(value = "/getDevNum")
    public Object getDevNum(String type) {
        return success(iotService.getDevNum(type));
    }


    @ApiOperation(value = "种植数据二级页面", notes = "参数: type=镇/村/果园")
    @GetMapping(value = "/getPlant")
    public Object getPlant(String type) {
        return success(iotService.getPlant(type));
    }

    @ApiOperation(value = "根据名字获取对应的品种占比信息", notes = "参数: type=镇/村/果园, name=镇名/村名/果园名")
    @GetMapping(value = "/getPlantInfo")
    public Object getPlantInfo(String type, String name) {
        return success(iotService.getPlantInfo(type, name));
    }





}
